	package com.niuwa.p2p.service.iml.springsecurity;
	
	import java.util.ArrayList;
	import java.util.Collection;
	import java.util.HashMap;
	import java.util.Iterator;
	import java.util.List;
	import java.util.Map;
	import org.springframework.security.access.ConfigAttribute;
	import org.springframework.security.access.SecurityConfig;
	import org.springframework.security.web.FilterInvocation;
	import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
	import org.springframework.security.web.util.AntUrlPathMatcher;
	import org.springframework.security.web.util.UrlMatcher;
	import org.springframework.stereotype.Service;
	import com.niuwa.p2p.entity.resource.Resource;
	import com.niuwa.p2p.entity.role.Role;
	import com.niuwa.p2p.service.resource.ResourcesService;
	import com.niuwa.p2p.service.role.RoleService;
	
	/**
	 * 
	 * 加载资源与权限的对应关系
	 * 
	 * @version 1.0
	 * @2015年2月6日
	 * @author zoudongfang
	 *
	 */
	@Service
	public class MySecurityMetadataSource implements
			FilterInvocationSecurityMetadataSource {
	
		private RoleService roleService;
	
		private ResourcesService resourcesService;
	
		// url对比
		private UrlMatcher urlMatcher = new AntUrlPathMatcher();
	
	
		/**
		 * 构造方法
		 * 
		 * @param roleDao
		 * @param resourcesDao
		 */
		public MySecurityMetadataSource(RoleService roleService,
				ResourcesService resourcesService) {
			this.roleService = roleService;
			this.resourcesService = resourcesService;
		  
		}
	
		
	
		@Override
		public Collection<ConfigAttribute> getAllConfigAttributes() {
	
			return null;
		}
	
		/**
		 * 
		 * 应当是资源为key， 权限为value。 资源通常为url， 权限就是那些以ROLE_为前缀的角色。 一个资源可以由多个权限来访问。
		 */
		@Override
		public Collection<ConfigAttribute> getAttributes(Object object)
				throws IllegalArgumentException {
			// object 是一个URL，被用户请求的url。
			String url = ((FilterInvocation) object).getRequestUrl();
		  
	
			int firstQuestionMarkIndex = url.indexOf("?");
	
			if (firstQuestionMarkIndex != -1) {
				url = url.substring(0, firstQuestionMarkIndex);
			}
	
			Iterator<String> ite = MyUserDetailServiceImpl.resourceMap.keySet().iterator();
	
			while (ite.hasNext()) {
	
				String resURL = ite.next();
	
				if (urlMatcher.pathMatchesUrl(url, resURL)) {
	
					return MyUserDetailServiceImpl.resourceMap.get(resURL);
				}
			}
	
			return null;
		}
	
		@Override
		public boolean supports(Class<?> arg0) {
	
			return true;
		}
	
		public RoleService getRoleService() {
			return roleService;
		}
	
		public void setRoleService(RoleService roleService) {
			this.roleService = roleService;
		}
	
		public ResourcesService getResourcesService() {
			return resourcesService;
		}
	
		public void setResourcesService(ResourcesService resourcesService) {
			this.resourcesService = resourcesService;
		}
	
	}
